package com.destroyer.common.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.destroyer.common.exception.ServiceException;
import java.util.ArrayList;
import java.util.List;

/**
 * 标题：TreeUtils
 * 说明：
 * 时间：2023/7/4
 * 作者：admin
 */
public class TreeUtils {
    /**
     * @param req        列表集合
     * @param primaryKey 主键名称
     * @param pidKey     pid 名称
     * @return
     */
    public static List getTreeList(List req, String primaryKey, String pidKey, Class c) {
        List rsp = new ArrayList();
        if (null == req || req.size() == 0) {
            return rsp;
        }
        //统一转换为jsonarray
        JSONArray mainDatas = JSONArray.parseArray(JSONArray.toJSONString(req, SerializerFeature.WriteNullStringAsEmpty));
        //筛选出首节点
        for (int i = 0; i < mainDatas.size(); i++) {
            JSONObject node = mainDatas.getJSONObject(i);
            Long pid = 0L;
            try {
                pid = node.getLong(pidKey);
            } catch (Exception e) {
                throw new ServiceException("PID 转化出参！");
            }
            if (null == pid) {
                throw new ServiceException("未获取到PID参数！");
            }
            if (pid.equals(0L)) {
                List childNodes = new ArrayList();
                childNodes = getChildNode(req, node.getLong(primaryKey), primaryKey, pidKey, c);
                if (null != childNodes && childNodes.size() > 0) {
                    node.put("children", childNodes);
                } else {
                    node.put("children", null);
                }

                rsp.add(JSON.parseObject(JSON.toJSONString(node), c));
            }
        }
        return rsp;

    }

    /**
     * 获取子节点
     *
     * @param datas
     * @param id
     * @return
     */
    private static List getChildNode(List datas, Long id, String primaryKey, String pidKey, Class c) {
        List rsp = new ArrayList();
        for (int i = 0; i < datas.size(); i++) {
            JSONObject node = JSON.parseObject(JSON.toJSONString(datas.get(i)));
            Long pid = node.getLong(pidKey);
            if (null != pid && !pid.equals(0L) && id.equals(pid)) {
                Long nodeId = node.getLong(primaryKey);
                if (null != nodeId) {
                    List childNodes = new ArrayList();
                    childNodes = getChildNode(datas, nodeId, primaryKey, pidKey, c);
                    if (null != childNodes && childNodes.size() > 0) {
                        node.put("children", childNodes);
                    } else {
                        node.put("children", null);
                    }
                }
                rsp.add(JSON.parseObject(JSON.toJSONString(node), c));

            }
        }
        return rsp;
    }


}
